package com.tiza.xiaoyoubao.ui.fragment;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;

import com.tianze.library.base.BaseFragment;
import com.tiza.xiaoyoubao.MainActivity;
import com.tiza.xiaoyoubao.R;
import com.tiza.xiaoyoubao.app.UIHelper;
import com.tiza.xiaoyoubao.entity.TaskShipMentsInfo;
import com.tiza.xiaoyoubao.entity.TbTaskShipMentsInfo;
import com.tiza.xiaoyoubao.net.ApiHttpClient;
import com.tiza.xiaoyoubao.net.JsonCallback;
import com.tiza.xiaoyoubao.net.ResponseInfo;
import com.tiza.xiaoyoubao.utils.DateUtils;
import com.tiza.xiaoyoubao.utils.ImageUtils;

import java.io.File;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Request;

import static android.app.Activity.RESULT_OK;

/**
 * Created by mapple on 17/3/5.
 * 评价
 */

public class EvaFragment extends BaseFragment {

    @BindView(R.id.iv_evaluation)
    ImageView iv_evaluation;
    @BindView(R.id.iv_logistics)
    ImageView iv_logistics;

    private TaskShipMentsInfo taskShipMentsInfo;
    private TbTaskShipMentsInfo mTbTaskShipMentsInfo;
    Bundle args;

    /**
     * 选择图片的返回码
     */
    public final static int SELECT_IMAGE_RESULT_CODE = 200;
    String[] proj = {MediaStore.MediaColumns.DATA};
    /**
     * 当前选择的图片的路径
     */
    public String mImagePath;

    private int i = 0;
    private File image1, image2;
    private Bitmap bitmap1, bitmap2;
    private String type, id, orderId, addTime;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        args = getArguments();
        type = args.getString("type");
        switch (type) {
            case "tbtask":
                mTbTaskShipMentsInfo = (TbTaskShipMentsInfo) args.getSerializable("info");
                id = String.valueOf(mTbTaskShipMentsInfo.getId());
                orderId = mTbTaskShipMentsInfo.getOrderid();
                addTime = DateUtils.getDateToStringSec(mTbTaskShipMentsInfo.getAddTime());
                break;
            case "taobaoTask":
                taskShipMentsInfo = (TaskShipMentsInfo) args.getSerializable("info");
                id = String.valueOf(taskShipMentsInfo.getId());
                orderId = taskShipMentsInfo.getOrderid();
                addTime = DateUtils.getDateToStringSec(taskShipMentsInfo.getAddTime());
                break;
        }

    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_eva;
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initView() {

    }

    @OnClick({R.id.view_evaluation, R.id.view_logistics, R.id.btn_commit})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.view_evaluation:
                i = 1;
                pickPhoto();
                break;
            case R.id.view_logistics:
                i = 2;
                pickPhoto();
                break;
            case R.id.btn_commit:
                String message = checkMessage();
                if (!TextUtils.isEmpty(message)) {
                    toast(message);
                    return;
                }
                insertDianFuTask4();
                break;
            default:
                break;
        }

    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == SELECT_IMAGE_RESULT_CODE && resultCode == RESULT_OK) {
            String imagePath = "";
            Uri uri = null;
            if (data != null && data.getData() != null) {// 有数据返回直接使用返回的图片地址
                uri = data.getData();
                Cursor cursor = getActivity().getContentResolver().query(uri, proj, null, null,
                                                                         null
                );
                if (cursor == null) {
                    uri = ImageUtils.getUri(getActivity(), data);
                }
                imagePath = ImageUtils.getFilePathByFileUri(getActivity(), uri);
            } else {// 无数据使用指定的图片路径
                imagePath = mImagePath;
                int i = ImageUtils.parseImageDegree(imagePath);
                System.out.println("旋转的角度:" + i);

            }
            //获取图片缩略图，避免OOM
            Bitmap bitmap = ImageUtils.getImageThumbnail(imagePath, ImageUtils.getWidth(
                    getActivity().getApplicationContext()) / 3 - 5, ImageUtils.getWidth(
                    getActivity().getApplicationContext()) / 3 - 5);
            if (i == 1) {
                image1 = new File(imagePath);
                bitmap1 = ImageUtils.rotateBitmap(bitmap, ImageUtils.parseImageDegree(imagePath));
                iv_evaluation.setImageBitmap(bitmap1);
            } else if (i == 2) {
                image2 = new File(imagePath);
                bitmap2 = ImageUtils.rotateBitmap(bitmap, ImageUtils.parseImageDegree(imagePath));
                iv_logistics.setImageBitmap(bitmap2);
            }

        }
    }

    /***
     * 从相册中取图片
     */
    public void pickPhoto() {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");
        getActivity().startActivityForResult(intent, SELECT_IMAGE_RESULT_CODE);
    }

    private void insertDianFuTask4() {
        ApiHttpClient.insertDianFuTask4(this, id, orderId, addTime, image1, image2,
                                        new JsonCallback<String>(String.class, true) {

                                            @Override
                                            public void onBefore(Request request) {
                                                super.onBefore(request);
                                                showWaitingDialog();
                                            }

                                            @Override
                                            public void onError(Call call, Exception e) {
                                                toast("网络异常，请检查后再试");
                                            }

                                            @Override
                                            public void onResponse(ResponseInfo<String> response) {
                                                int code = response.getCode();
                                                if (code == 1) {
                                                    showWarnDialog(response.getMessage());
                                                    return;
                                                }

                                                toast("评价提交成功");
                                                upDateTask();

                                            }

                                            @Override
                                            public void onAfter() {
                                                super.onAfter();
                                                hideWaitingDialog();
                                            }
                                        }
        );
    }


    private void upDateTask() {
        ApiHttpClient.setUpdateTask(this, orderId, "5",
                                    new JsonCallback<String>(String.class, true) {

                                        @Override
                                        public void onBefore(Request request) {
                                            super.onBefore(request);
                                        }

                                        @Override
                                        public void onError(Call call, Exception e) {
                                            toast("网络连接失败,请稍后再试");
                                        }

                                        @Override
                                        public void onResponse(ResponseInfo<String> response) {
                                            int code = response.getCode();
                                            String message = response.getMessage();
                                            if (code == 1) {
                                                showWarnDialog(message);
                                                return;
                                            }
                                            UIHelper.show(getActivity(), MainActivity.class, true);
                                            finish();
                                        }

                                        @Override
                                        public void onAfter() {
                                            super.onAfter();
                                        }
                                    }
        );
    }

    private String checkMessage() {
        if (bitmap1 == null || bitmap2 == null) return "请选择要上传的照片";
        return "";
    }
}
